require("behaviours/wander")
require("behaviours/faceentity")
require("behaviours/leash")

local MAX_WANDER_DIST = 4          -- 平常游荡范围
local LEASH_RETURN_DIST = 8        -- 超出该距离就会返回
local LEASH_RETURN_STOP_DIST = 2   -- 回到生成点后停止的距离
local FACE_DIST = TUNING.RESEARCH_MACHINE_DIST

local WanderingTraderBrain = Class(Brain, function(self, inst)
    Brain._ctor(self, inst)
end)

----------------------------------------------------------------------
-- 面向最近的玩家（在交易或聊天时）
----------------------------------------------------------------------
local function GetFaceTargetFn(inst)
    return FindClosestPlayerToInst(inst, FACE_DIST, true)
end

local function KeepFaceTargetFn(inst, target)
    return inst:IsNear(target, FACE_DIST)
end

----------------------------------------------------------------------
-- 获取返回目标点（嗨猪生成点）
----------------------------------------------------------------------
local function GetHomePos(inst)
    return inst.spawn_point or inst:GetPosition()
end

----------------------------------------------------------------------
-- 初始化大脑行为树
----------------------------------------------------------------------
function WanderingTraderBrain:OnStart()
    -- 确保嗨猪记录了自己的出生点
    if not self.inst.spawn_point then
        self.inst.spawn_point = self.inst:GetPosition()
    end

    local root = PriorityNode({

        ------------------------------------------------------------------
        -- 如果正在交易或有货物，就面向玩家
        ------------------------------------------------------------------
        WhileNode(function() return self.inst.sg.mem.trading or self.inst:HasStock() end, "Trading",
            FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn)),

        ------------------------------------------------------------------
        -- 没货的时候随机喊话并面向玩家
        ------------------------------------------------------------------
        IfNode(function() return not self.inst:HasStock() and self.inst:CanChatter() end, "No stock left",
            SequenceNode({
                ActionNode(function()
                    self.inst:DoChatter("BBOY_PIGGY_HI_OUTOFSTOCK_PROXIMITY",
                        math.random(#STRINGS.BBOY_PIGGY_HI_OUTOFSTOCK_PROXIMITY), 15)
                end),
                FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn, 2),
            })
        ),

        ------------------------------------------------------------------
        -- 限制活动范围：超出 8 格则返回出生点
        ------------------------------------------------------------------
        Leash(self.inst, GetHomePos, LEASH_RETURN_DIST, LEASH_RETURN_STOP_DIST),

        ------------------------------------------------------------------
        -- 在出生点周围 4 格范围内自由漫步
        ------------------------------------------------------------------
        Wander(self.inst, GetHomePos, MAX_WANDER_DIST),

    }, 0.25)

    self.bt = BT(self.inst, root)
end

return WanderingTraderBrain
